﻿using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Atha.Contracts;

namespace Atha.Languages.PowerShell
{
	public sealed class PowerShellTestRunContext : ScriptTestRunContextBase
	{
		public PowerShellTestRunContext(string name, string script)
			: base(name, script)
		{
		}

		protected override void OnExecute(string script, ITestRunResultBuilder testRunResultBuilder)
		{
			try
			{
				var executionCtx = new PascalCaseTestExecutionContext(testRunResultBuilder);

				var runspace = RunspaceFactory.CreateRunspace();

				runspace.Open();

				runspace.SessionStateProxy.SetVariable("atha", executionCtx);

				var pipeline = runspace.CreatePipeline();

				pipeline.Commands.AddScript(script);

				var results = pipeline.Invoke();

				runspace.Close();
			}
			catch (CommandNotFoundException commandNotFoundException)
			{
				testRunResultBuilder.AddResult(new SyntaxExceptionTestResult(commandNotFoundException.ErrorRecord.InvocationInfo.ScriptLineNumber, commandNotFoundException.ErrorRecord.InvocationInfo.OffsetInLine, commandNotFoundException));
			}
		}
	}
}